/*
 * Copyright (C) 2013 Andreas Stuetz <andreas.stuetz@gmail.com>
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.zbbt.sportslottery.ui.fragment;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.LinearLayout;

import com.gc.materialdesign.views.ProgressBarCircularIndetermininate;
import com.google.gson.JsonObject;
import com.zbbt.sportslottery.R;
import com.zbbt.sportslottery.app.App;
import com.zbbt.sportslottery.app.Constant;
import com.zbbt.sportslottery.app.ServerConfig;
import com.zbbt.sportslottery.bean.News;
import com.zbbt.sportslottery.bean.SuperResult;
import com.zbbt.sportslottery.db.DbManager;
import com.zbbt.sportslottery.net.TypeGsonHttpHandler;
import com.zbbt.sportslottery.net.ZbHttpClient;
import com.zbbt.sportslottery.ui.activity.GameDataActivity;
import com.zbbt.sportslottery.ui.adapter.HomeRecyclerAdapter;
import com.zbbt.sportslottery.ui.widget.FooterRecyclerView;
import com.zbbt.sportslottery.ui.widget.recycler.MyItemClickListener;
import com.zbbt.sportslottery.ui.widget.swipe.SwipeRefreshLayout;
import com.zbbt.sportslottery.ui.widget.swipe.SwipeRefreshLayout.OnRefreshListener;
import com.zbbt.sportslottery.util.AppUtil;
import com.zbbt.sportslottery.util.LogUtil;
import com.zbbt.sportslottery.util.UmengUtil;

/**
 * @author kangle 首页栏目
 */

public class ChildHomeFragment extends SimpleBaseFragment {

	private static final String ARG_POSITION = "position";
	private static final String PROGRAMAID_NUM = "programaIdNum";
	private ViewPager viewPager4Focus;
	private List<View> pageViewsList = new ArrayList<View>();// 存放焦点图片
	private final int NEXT_FOCUS = 2;// 更换图片的消息的标志
	private final int TEME = 5000;// 每张图片停留的时间
	private HomeRecyclerAdapter listAdapter = null;
	private List<News> homeListData = new ArrayList<News>();// 列表数据
	private LayoutInflater inflater;
	private String pageSize = "10";
	private int curPage = 1;
	private boolean available = false;
	private RecyclerView homeList;
	private SwipeRefreshLayout mSwipeRefreshLayout;
	private int pageTotal = 0;// 读取本地缓存翻页 当前页数
	private int thisPageSize = 10;// 读取本地缓存翻页 一页10条
	private boolean hasmore_data = true;// 是否有下一页数据
	private ProgressBarCircularIndetermininate progressBar;
	private View tabhost;
	private int mToolbarHeight;
	private int paddingTop;
	private int paddingbottem;

	private int tabIndex;
	private int programaIdNum = 1;// 默认栏目为第一个
	private LinearLayout error_layout;
	private boolean isrefresh = false;
	private int totalPage = 0;

	public static ChildHomeFragment newInstance(int position, int num) {
		ChildHomeFragment f = new ChildHomeFragment();
		Bundle b = new Bundle();
		b.putInt(ARG_POSITION, position);
		b.putInt(PROGRAMAID_NUM, num);
		f.setArguments(b);
		return f;
	}

	@Override
	protected void initView(LayoutInflater inflater) {
		this.inflater = inflater;
		// TODO Auto-generated method stub
		tabIndex = getArguments().getInt(ARG_POSITION);
		programaIdNum = getArguments().getInt(PROGRAMAID_NUM);
		mView = inflater.inflate(R.layout.fragment_childhome, null);
		error_layout = (LinearLayout) findViewById(R.id.error_layout);
		progressBar = (ProgressBarCircularIndetermininate) findViewById(R.id.progressBarCircularIndetermininate);
		mSwipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipe_container);
		tabhost = (View) getActivity().findViewById(android.R.id.tabs);
		homeList = (RecyclerView) findViewById(R.id.home_list);
		paddingbottem = tabhost.getHeight();
		homeList.setPadding(homeList.getPaddingLeft(), homeList.getPaddingTop(), homeList.getPaddingRight(), tabhost.getHeight());
		homeList.setLayoutManager(new LinearLayoutManager(getActivity()));
		homeList.setHasFixedSize(false);
		mToolbarHeight = AppUtil.getToolbarHeight(getActivity());
		listAdapter = new HomeRecyclerAdapter(homeListData, getActivity());
		listAdapter.setOnBottomClickListener(new HomeRecyclerAdapter.OnBottomClickListener() {
			@Override
			public void onBottomClick(RecyclerView.ViewHolder viewHolder, int position) {
				if (!isrefresh) {
					((FooterRecyclerView) viewHolder).bottom_tx.setVisibility(View.VISIBLE);
					if (hasmore_data == true) {
						if (totalPage > 1) {
							getHomeListData(Constant.HAS_MORE);
						}
					} else {
						if (homeListData != null && homeListData.size() > 0) {
							((FooterRecyclerView) viewHolder).bottom_tx.setText("暂无更多数据");
						} else {
							((FooterRecyclerView) viewHolder).bottom_tx.setText("该栏目暂无数据");
						}
					}
				}
			}
		});
		homeList.setAdapter(listAdapter);
		listAdapter.setOnItemClickListener(onItemClickListener);
		// homeList.setOnScrollListener(new HidingScrollListener() {
		// @Override
		// public void onHide() {
		// tabhost.animate().translationY(paddingbottem).setInterpolator(new
		// AccelerateInterpolator(2)).start();
		// }
		//
		// @Override
		// public void onShow() {
		// tabhost.animate().translationY(0).setInterpolator(new
		// DecelerateInterpolator(2)).start();
		// }
		// });
		mSwipeRefreshLayout.setOnRefreshListener(new OnRefreshListener() {
			@Override
			public void onRefresh() {
				if (!isrefresh) {
					hasmore_data = true;
					getHomeListData(Constant.REFRESH);
				}
			}
		});
		progressBar.setVisibility(View.VISIBLE);
		getHomeListData(Constant.REFRESH);
		listAdapter.notifyDataSetChanged();
		
		if(App.PARAM_SDK_VERSION <=10){
			mSwipeRefreshLayout.setEnabled(false);
		}
	}

	@Override
	public void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		available = true;
		handler.sendEmptyMessageDelayed(NEXT_FOCUS, TEME);// 给handler发送一个延时更换消息

		if (Constant.isShowStatic == true) {
			if (listAdapter != null) {
				listAdapter.notifyDataSetChanged();
			}
		}
		// if (App.citychange == true) {
		// hasmore_data = true;
		// getHomeListData(Constant.REFRESH);
		// }
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see totem.app.BaseFragment#onPause()
	 */
	@Override
	public void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		available = false;
	}

	@Override
	protected void setListener() {
		error_layout.setOnClickListener(this);
	}

	/**
	 * 异步信息处理器
	 */
	private Handler handler = new Handler() {
		@Override
		public void handleMessage(android.os.Message msg) {

			if (available) {
				switch (msg.what) {
				case NEXT_FOCUS:
					if (pageViewsList.size() > 1) {
						viewPager4Focus.setCurrentItem(viewPager4Focus.getCurrentItem() + 1);
					}
					handler.removeMessages(NEXT_FOCUS);
					handler.sendEmptyMessageDelayed(NEXT_FOCUS, TEME);
					break;
				}
			}
		};
	};

	@Override
	protected void initData() {
		// TODO Auto-generated method stub

	}

	@Override
	protected void onClickEvent(View v) {
		switch (v.getId()) {
		case R.id.error_layout:
			progressBar.setVisibility(View.VISIBLE);
			getHomeListData(Constant.REFRESH);
			break;
		default:
			break;
		}
	}

	/**
	 * 获取首页列表数据
	 */
	private void getHomeListData(final int method) {
		isrefresh = true;
		if (method == Constant.REFRESH) {
			mSwipeRefreshLayout.setRefreshing(true);
			curPage = 1;
		} else if (method == Constant.HAS_MORE) {
			if (homeListData != null) {
				if (homeListData.size() > 0) {
					curPage++;
				}
			}
		}
		JsonObject jsonObject = new JsonObject();
		jsonObject.addProperty("curPage", curPage);
		jsonObject.addProperty("pageSize", pageSize);
		jsonObject.addProperty("programaId", programaIdNum);
		ZbHttpClient.postNewApi(ServerConfig.API_NEWS_LIST, jsonObject, new TypeGsonHttpHandler<SuperResult<News>>(true) {

			@Override
			public void onSuccess(SuperResult<News> data) {
				if (data != null) {
					if (tabIndex == 0) {
						Iterator<News> iterable = data.getData().iterator();
						while (iterable.hasNext()) {
							News news = iterable.next();
							news.setIshot(1);
						}
					}
					if (method == Constant.REFRESH) {
						if (data.getData() != null) {
							if (data.getData().size() > 0) {
								homeListData.clear();
								homeListData.addAll(data.getData());
							}
						}
					} else if (method == Constant.HAS_MORE) {
						homeListData.addAll(data.getData());
					}
					totalPage = data.getTotalPage();
					if (data.getTotalPage() > curPage) {
						hasmore_data = true;
					} else {
						hasmore_data = false;
					}
					listAdapter.notifyDataSetChanged();
					if (tabIndex == 0) {
						DbManager.saveNewsList(homeListData, "1");
					} else {
						DbManager.saveNewsList(homeListData, HomeFragment.channelItems.get(tabIndex).getProgramaId() + "");
					}
					error_layout.setVisibility(View.GONE);
					progressBar.setVisibility(View.GONE);
					mSwipeRefreshLayout.setRefreshing(false);
				}
				isrefresh = false;
			}

			@Override
			public void onFailure(String errorCode, String errorMsg) {
				mSwipeRefreshLayout.setRefreshing(false);
				progressBar.setVisibility(View.GONE);
				if (errorMsg.equals("没有您要查询的数据")) {
					homeListData.clear();
					listAdapter.notifyDataSetChanged();
					hasmore_data = false;
				}
				if (method == Constant.HAS_MORE) {
					pageTotal++;
					getHomeLocalList();
				} else {
					pageTotal = 0;
					homeListData.clear();
					getHomeLocalList();
				}
				isrefresh = false;
			}
		});
	}

	/**
	 * 获取首页列表本地缓存数据
	 */
	@SuppressWarnings("unused")
	public void getHomeLocalList() {
		List<News> listdata = null;
		// 因为热点的programaid分别是其他栏目的programaid，不是唯一的，所以要单独处理，当tabindex==0（热点的fragment）
		if (tabIndex == 0) {
			listdata = DbManager.getNewsList("1", thisPageSize, pageTotal);
		} else {
			listdata = DbManager.getNewsList(HomeFragment.channelItems.get(tabIndex).getProgramaId() + "", thisPageSize, pageTotal);
		}
		if (listdata != null) {
			if (listdata.size() > 0) {
				homeListData.addAll(listdata);
				LogUtil.defLog("DbManager_list==" + homeListData.toString());
				listAdapter.notifyDataSetChanged();
				error_layout.setVisibility(View.GONE);
			} else {
				hasmore_data = false;
			}
		} else {
			error_layout.setVisibility(View.VISIBLE);
		}
	}

	private MyItemClickListener onItemClickListener = new MyItemClickListener() {

		@Override
		public void onitemClick(View view, int position) {
			LogUtil.defLog("onItemClick(postion=" + position + "homeListData.size()=" + homeListData.size());
			// 跳转到资讯详情
			if (position < 0 || position >= homeListData.size()) {
				return;
			}
			DbManager.saveNewsRead(homeListData.get(position).getNewsId() + "");
			Constant.isShowStatic = true;
			Intent intent = new Intent(getActivity(), GameDataActivity.class);
			intent.putExtra("Url", homeListData.get(position).getNewsUrl());
			intent.putExtra("Title", HomeFragment.channelItems.get(tabIndex).getName());
			intent.putExtra("ShowShare", true);
			if (homeListData.get(position).getNewsImg() != null && homeListData.get(position).getNewsImg().size() > 0) {
				intent.putExtra("ImageUrl", homeListData.get(position).getNewsImg().get(0).getImgUrl());
			}
			intent.putExtra("ShareTitle", homeListData.get(position).getNewsTitle());
			intent.putExtra("SummaryTx", homeListData.get(position).getNewsModel());
			UmengUtil.onEvent(context, Constant.UMENG_NEWS_TJ+HomeFragment.channelItems.get(tabIndex).getProgramaId());
			getActivity().startActivity(intent);
			
		}
	};

}